package com.michaelwolf.mytool.csenvsimulator;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;

import com.michaelwolf.mytool.csenvsimulator.CustomerDataLoader.QueryRecord;
import com.michaelwolf.mytool.util.GZIPTool;

public class CustomerRecordDisplayer extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JPanel controlPanel = new JPanel();
	private JComboBox<CommandDropdownItem> commandDropdown = new JComboBox<>();
	private JComboBox<String> commandTimestampDropdown = new JComboBox<>();
	private JLabel compKeyword = new JLabel("Keyword :");
	private JTextField compKeywordInput = new JTextField();
	private JButton searchButton = new JButton("Search Customer Record");
	
	private JButton fileButton = new JButton("Choose Record File To Load");
	
	JFileChooser jfc=new JFileChooser();
	
	
	private JTextPane contentPane = new JTextPane();
	private JScrollPane scrollPane = new JScrollPane(contentPane);
	private CustomerDataLoader loader = new CustomerDataLoader();
	
	//private String fileName = "E:\\2017-12-08_110957.txt";
	
	public CustomerRecordDisplayer() throws IOException{
		super("CS Rocord Reader");
		setSize(2000, 1000);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		controlPanel.setLayout(null);
		
		compKeyword.setBounds(10, 30, 60, 30);
		controlPanel.add(compKeyword);
		compKeywordInput.setBounds(80, 30, 200, 30);
		controlPanel.add(compKeywordInput);
		searchButton.setBounds(290, 30, 200, 30);
		controlPanel.add(searchButton);
		
		fileButton.setBounds(800, 30, 160, 30);
		controlPanel.add(fileButton);
		
		fileButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );  
		        jfc.showDialog(new JLabel(), "choose file");  
		        File file=jfc.getSelectedFile();  
		        if(file.isDirectory()){  
		            for(File recordfile : file.listFiles()){
		            	if(recordfile.isFile()){
		            		if(recordfile.getName().endsWith(".gz")){
		            			try {
									GZIPTool.doUncompressFile(recordfile.getAbsolutePath());
									String uncompressFileName = recordfile.getAbsolutePath().substring(0, recordfile.getAbsolutePath().length()-3);
									File uncompressFile = new File(uncompressFileName);
									loader.loadRecordFile(uncompressFile);
									uncompressFile.delete();
								} catch (Exception e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
		            		}else if(recordfile.getName().endsWith(".txt")){
		            			try {
									loader.loadRecordFile(recordfile);
								} catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
			            	}
		            		
		            		
							
		            	}
		            }
		            initCommandDropdown();
					initCommandTimestapDropdown();
					initContentPane();
		        }else if(file.isFile()){
		        	if(file.getName().endsWith(".txt")){
		        		loadFileAndInitUI(file);
		        	}else if(file.getName().endsWith(".gz")){
		        		uncompressAndLoadInitUI(file);
		        	}
		        }  
			}

			private void uncompressAndLoadInitUI(File file) {
				try {
					GZIPTool.doUncompressFile(file.getAbsolutePath());
					String uncompressFileName = file.getAbsolutePath().substring(0, file.getAbsolutePath().length()-3);
					File uncompressFile = new File(uncompressFileName);
					loadFileAndInitUI(uncompressFile);
					
					uncompressFile.delete();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}

			private void loadFileAndInitUI(File file) {
				try {
					loader.loadRecordFile(file);
					initCommandDropdown();
					initCommandTimestapDropdown();
					initContentPane();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			
		});
		
		commandDropdown.setBounds(10, 80, 1955, 30);
		controlPanel.add(commandDropdown);
		
		
		
		
		commandTimestampDropdown.setBounds(10, 110, 1000, 30);
		controlPanel.add(commandTimestampDropdown);
		
		scrollPane.setBounds(10, 150, 965, 800);
		scrollPane
		.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		scrollPane
		.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		
		controlPanel.add(scrollPane);
		
		
		
		
		
		add(controlPanel);
		setVisible(true);
		
		//loader.loadRecordFile(fileName);
		
		
		
		searchButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				String keyword = compKeywordInput.getText();
				commandDropdown.removeAllItems();
				
				for(String commandKey : loader.getQueryCommandList()){
					if(commandKey.contains(keyword)){
						commandDropdown.addItem(new CommandDropdownItem(commandKey));
					}
				}
				
			}
			
		});
		
		commandDropdown.addItemListener(new ItemListener(){

			@Override
			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				if (ItemEvent.SELECTED == e.getStateChange()) {
					initCommandTimestapDropdown();
				}
			}

			
			
		});
		
		commandTimestampDropdown.addItemListener(new ItemListener(){

			@Override
			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				if (ItemEvent.SELECTED == e.getStateChange()) {
					initContentPane();
				}
			}

			
			
		});
		
		
	}

	private void initCommandDropdown() {
		for(String commandKey : loader.getQueryCommandList()){
			
			commandDropdown.addItem(new CommandDropdownItem(commandKey));
		}
	}
	
	private void initContentPane() {
		CommandDropdownItem selectedCommandDropdownItem = (CommandDropdownItem)commandDropdown.getSelectedItem();
		String selectedCommand = selectedCommandDropdownItem.getCommand();
		String selectedCommandTimeStamp = (String)commandTimestampDropdown.getSelectedItem();
		
		QueryRecord record = loader.getQueryCmmandRecord(selectedCommand, selectedCommandTimeStamp);
		
		contentPane.setText(convertEscape(record.getCommand() + record.getCommandOutput()));
	}
	
	private void initCommandTimestapDropdown() {
		CommandDropdownItem selectedCommandDropdownItem = (CommandDropdownItem)commandDropdown.getSelectedItem();
		String selectedCommand = selectedCommandDropdownItem.getCommand();
		Set<String> commandtimestampSet = loader.getQueryCommandTimestampSet(selectedCommand);
		
		commandTimestampDropdown.removeAllItems();
		for(String timestamp : commandtimestampSet){
			commandTimestampDropdown.addItem(timestamp);
		}
	}
	
	private String convertEscape(String source){
		source = source.replaceAll("\\\\u003c", "<");
		source = source.replaceAll("\\\\u003e", ">");
		source = source.replaceAll("\\\\u003d", "=");
		source = source.replaceAll("\\\\\"", "\"");
		source = source.replaceAll("\\\\n", "\n");
		source = source.replaceAll("\\\\r", "\r");
		return source;
	}
	
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		new CustomerRecordDisplayer();
	}
	
	class CommandDropdownItem{
		String command;
		
		public String getCommand() {
			return command;
		}

		public CommandDropdownItem(String command) {
			super();
			this.command = command;
		}
		
		public String toString(){
			return convertEscape(command);
		}
	}

}
